// 增强功能核心脚本
var themeLocalStorageKey = 'docdash-theme';
var fontSizeLocalStorageKey = 'docdash-font-size';
var html = document.querySelector('html');
var MAX_FONT_SIZE = 24;
var MIN_FONT_SIZE = 12;
var localStorage = window.localStorage;

// 主题管理
function getTheme() {
    var theme = localStorage.getItem(themeLocalStorageKey);
    return theme || 'light';
}

function updateTheme(theme) {
    var body = document.body;
    var svgUse = document.querySelectorAll('.theme-svg-use');
    var iconID = theme === 'dark' ? '#light-theme-icon' : '#dark-theme-icon';

    body.setAttribute('data-theme', theme);
    svgUse.forEach(function (svg) {
        svg.setAttribute('xlink:href', iconID);
    });

    localStorage.setItem(themeLocalStorageKey, theme);
}

function toggleTheme() {
    var currentTheme = getTheme();
    var newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    updateTheme(newTheme);
}

// 初始化主题
function initTheme() {
    var currentTheme = getTheme();
    updateTheme(currentTheme);
}



function updateFontSize(fontSize) {
    // 同时设置html和body的字体大小
    html.style.fontSize = fontSize + 'px';
    document.body.style.fontSize = fontSize + 'px';
    localStorage.setItem(fontSizeLocalStorageKey, fontSize);

    // 更新字体大小显示
    var fontSizeText = document.querySelector('.font-size-text');
    if (fontSizeText) {
        fontSizeText.textContent = fontSize;
    }
}

function getFontSize() {
    var currentFontSize = 16;
    try {
        // 优先从body元素获取字体大小
        var bodyFontSize = document.body.style.fontSize;
        if (bodyFontSize) {
            currentFontSize = Number.parseInt(bodyFontSize.split('px')[0], 10);
        } else {
            // 如果body元素没有设置fontSize，则从localStorage读取
            var stored = localStorage.getItem(fontSizeLocalStorageKey);
            if (stored) {
                currentFontSize = parseInt(stored, 10);
            }
        }
    } catch (e) {
        console.log(e);
    }
    return currentFontSize;
}
function incrementFont() {
    var currentSize = getFontSize();
    if (currentSize < MAX_FONT_SIZE) {
        updateFontSize(currentSize + 1);
    }
}

function decrementFont() {
    var currentSize = getFontSize();
    if (currentSize > MIN_FONT_SIZE) {
        updateFontSize(currentSize - 1);
    }
}

function resetFont() {
    updateFontSize(16);
}

// 初始化字体大小
function initFontSize() {
    var currentFontSize = getFontSize();
    updateFontSize(currentFontSize);
}

// 字体调整弹窗
function createFontSizeTooltip() {
    var fontSize = getFontSize();
    return `
        <div class="font-size-tooltip">
            <button class="icon-button ${fontSize <= MIN_FONT_SIZE ? 'disabled' : ''}" onclick="decrementFont()" aria-label="减小字体">
                <svg><use xlink:href="#minus-icon"></use></svg>
            </button>
            <div class="font-size-text">${fontSize}</div>
            <button class="icon-button ${fontSize >= MAX_FONT_SIZE ? 'disabled' : ''}" onclick="incrementFont()" aria-label="增大字体">
                <svg><use xlink:href="#plus-icon"></use></svg>
            </button>
            <button class="icon-button" onclick="resetFont()" aria-label="重置字体">
                <svg><use xlink:href="#reset-icon"></use></svg>
            </button>
        </div>
    `;
}

// 折叠功能相关常量和函数
var accordionLocalStorageKey = 'jsdoc-accordion-ids';

function setAccordionIdToLocalStorage(id) {
    var ids = getAccordionIdsFromLocalStorage();
    if (ids.indexOf(id) === -1) {
        ids.push(id);
        localStorage.setItem(accordionLocalStorageKey, JSON.stringify(ids));
    }
}

function removeAccordionIdFromLocalStorage(id) {
    var ids = getAccordionIdsFromLocalStorage();
    var index = ids.indexOf(id);
    if (index !== -1) {
        ids.splice(index, 1);
        localStorage.setItem(accordionLocalStorageKey, JSON.stringify(ids));
    }
}

function getAccordionIdsFromLocalStorage() {
    try {
        var ids = localStorage.getItem(accordionLocalStorageKey);
        return ids ? JSON.parse(ids) : [];
    } catch (e) {
        return [];
    }
}

function toggleAccordion(element) {
    var isOpen = element.getAttribute('data-isopen') === 'true';
    var sectionId = element.getAttribute('data-section');

    if (isOpen) {
        element.setAttribute('data-isopen', 'false');
        removeAccordionIdFromLocalStorage(sectionId);
    } else {
        element.setAttribute('data-isopen', 'true');
        setAccordionIdToLocalStorage(sectionId);
    }
}

// 修改initAccordion函数，只负责初始化状态，不添加事件监听器
function initAccordion() {
    var accordionElements = document.querySelectorAll('.with-arrow');
    var openIds = getAccordionIdsFromLocalStorage();

    accordionElements.forEach(function (element) {
        var sectionId = element.getAttribute('data-section');
        var section = element.closest('.sidebar-section');
        var container = section.querySelector('.sidebar-section-children-container');

        // 设置初始状态 - 如果没有保存的状态，默认展开
        if (openIds.length === 0 || openIds.indexOf(sectionId) !== -1) {
            element.setAttribute('data-isopen', 'true');
            if (container) {
                // 动态计算高度
                container.style.maxHeight = 'none';
                container.style.overflow = 'visible';
                var actualHeight = container.scrollHeight;
                container.style.maxHeight = actualHeight + 'px';
            }
        } else {
            element.setAttribute('data-isopen', 'false');
            if (container) {
                container.style.maxHeight = '0';
                container.style.overflow = 'hidden';
            }
        }
    });
}

// 添加搜索高亮功能
function highlightSearchTerm(text, searchTerm) {
    if (!searchTerm) return text;

    var regex = new RegExp('(' + searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
    return text.replace(regex, '<span class="search-highlight">$1</span>');
}


// 左侧搜索功能 - 参考minemap-docdash实现
var searchAttr = 'data-search-mode';

function contains(a, m) {
    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m) !== -1;
}

// 改进的菜单高亮功能 - 支持三级菜单
function initMenuHighlight() {
    var currentPath = window.location.pathname;
    var currentPage = currentPath.split('/').pop();

    // 移除所有当前高亮
    document.querySelectorAll('nav a.current').forEach(function (elem) {
        elem.classList.remove('current');
    });

    // 查找匹配的链接并高亮（包括三级菜单）
    document.querySelectorAll('nav .sidebar-section-children a').forEach(function (link) {
        var href = link.getAttribute('href');
        if (href && (href === currentPage || href.endsWith('/' + currentPage))) {
            link.classList.add('current');

            // 展开父级菜单
            var parentSection = link.closest('.sidebar-section');
            if (parentSection) {
                var titleElement = parentSection.querySelector('.sidebar-section-title');
                if (titleElement && titleElement.classList.contains('with-arrow')) {
                    titleElement.setAttribute('data-isopen', 'true');
                    setAccordionIdToLocalStorage(titleElement.getAttribute('data-section'));
                }
            }

            // 如果是三级菜单项，展开其父级二级菜单
            var parentLi = link.closest('li');
            if (parentLi) {
                var parentUl = parentLi.closest('ul');
                if (parentUl && (parentUl.classList.contains('methods') || parentUl.classList.contains('members'))) {
                    // 找到二级菜单项并展开
                    var secondLevelLi = parentUl.closest('li');
                    if (secondLevelLi) {
                        secondLevelLi.classList.add('expanded');
                        parentUl.style.display = 'block';
                    }
                }
            }
        }
    });

    // 页面加载完成后，滚动到当前菜单项的专业位置
    setTimeout(function () {
        scrollToCurrentMenuItem();
    }, 300); // 给足够时间让DOM完全渲染
}

// 统一的容器高度计算函数
function updateContainerHeight(container, delay = 0) {
    if (!container) return;

    setTimeout(function () {
        // 临时移除高度限制以获取真实高度
        const originalMaxHeight = container.style.maxHeight;
        const originalOverflow = container.style.overflow;

        container.style.maxHeight = 'none';
        container.style.overflow = 'visible';

        // 强制重新计算布局
        container.offsetHeight;

        // 使用requestAnimationFrame确保DOM完全更新
        requestAnimationFrame(function () {
            // 获取包含所有展开内容的真实高度
            const actualHeight = container.scrollHeight;

            // 恢复overflow设置
            container.style.overflow = originalOverflow || 'hidden';

            // 设置新的高度（添加缓冲空间）
            container.style.maxHeight = (actualHeight + 50) + 'px';

            // 延迟后移除高度限制，确保动画完成
            setTimeout(function () {
                const hasExpanded = container.querySelector('li.expanded');
                if (hasExpanded) {
                    container.style.maxHeight = 'none';
                }
            }, 350);
        });
    }, delay);
}

// 查找并更新所有相关容器的高度
function updateAllContainerHeights(delay = 0) {
    document.querySelectorAll('.sidebar-section-children-container').forEach(function (container) {
        const hasExpanded = container.querySelector('li.expanded');
        if (hasExpanded) {
            updateContainerHeight(container, delay);
        }
    });
}

// 菜单项点击处理 - 修复版本
function initMenuItemHandlers() {
    // 处理一级菜单折叠/展开
    document.querySelectorAll('.sidebar-section-title.with-arrow').forEach(function (title) {
        title.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var section = this.closest('.sidebar-section');
            var container = section.querySelector('.sidebar-section-children-container');
            var isOpen = this.getAttribute('data-isopen') === 'true';

            if (isOpen) {
                this.setAttribute('data-isopen', 'false');
                container.style.maxHeight = '0';
                container.style.overflow = 'hidden';
                removeAccordionIdFromLocalStorage(this.getAttribute('data-section'));
            } else {
                this.setAttribute('data-isopen', 'true');
                container.style.maxHeight = 'none';
                container.style.overflow = 'visible';
                var actualHeight = container.scrollHeight;
                container.style.maxHeight = actualHeight + 'px';
                setAccordionIdToLocalStorage(this.getAttribute('data-section'));
            }
        });
    });

    // 二级菜单点击处理
    document.querySelectorAll('.sidebar-section-children > li > a').forEach(function (secondLevelLink) {
        secondLevelLink.addEventListener('click', function (e) {
            const href = this.getAttribute('href');
            const parentItem = this.closest('li');
            const hasThirdLevel = parentItem.querySelector('.methods, .members');

            // 防抖处理
            clearTimeout(this.clickTimeout);
            this.clickTimeout = setTimeout(function () {
                // 类型1: 有三级菜单的展开/收缩
                if (hasThirdLevel) {
                    e.preventDefault();

                    // 清除其他二级菜单的current状态
                    document.querySelectorAll('.sidebar-section-children > li > a.current').forEach(function (link) {
                        if (link !== secondLevelLink) {
                            link.classList.remove('current');
                        }
                    });

                    // 收缩所有其他同级菜单
                    parentItem.parentElement.querySelectorAll('li').forEach(function (sibling) {
                        if (sibling !== parentItem) {
                            sibling.classList.remove('expanded');
                            const siblingThirdLevel = sibling.querySelectorAll('.methods, .members');
                            siblingThirdLevel.forEach(function (menu) {
                                menu.style.setProperty('display', 'none', 'important');
                                menu.style.visibility = 'hidden';
                                menu.querySelectorAll('li').forEach(function (li) {
                                    li.style.display = '';
                                    li.style.visibility = '';
                                });
                            });
                        }
                    });

                    // 切换当前菜单状态
                    const isExpanded = parentItem.classList.contains('expanded');
                    const thirdLevelMenus = parentItem.querySelectorAll('.methods, .members');

                    if (isExpanded) {
                        // 收缩当前菜单
                        parentItem.classList.remove('expanded');
                        thirdLevelMenus.forEach(function (menu) {
                            menu.style.setProperty('display', 'none', 'important');
                            menu.style.visibility = 'hidden';
                        });
                    } else {
                        // 展开当前菜单
                        parentItem.classList.add('expanded');
                        secondLevelLink.classList.add('current');

                        thirdLevelMenus.forEach(function (menu) {
                            menu.style.setProperty('display', 'block', 'important');
                            menu.style.visibility = 'visible';
                            menu.querySelectorAll('li').forEach(function (li) {
                                li.style.display = '';
                                li.style.visibility = '';
                            });
                        });
                    }

                    // 关键修复：立即更新容器高度
                    const container = parentItem.closest('.sidebar-section-children-container');
                    updateContainerHeight(container, 10);
                }
                // 类型2: 无三级菜单的直接导航链接
                else if (href && !href.startsWith('#')) {
                    sessionStorage.setItem('pendingMenuHighlight', href);

                    document.querySelectorAll('.sidebar-section-children a.current').forEach(function (link) {
                        link.classList.remove('current');
                    });
                    document.querySelectorAll('.sidebar-section-children li.expanded').forEach(function (item) {
                        item.classList.remove('expanded');
                        const thirdLevel = item.querySelectorAll('.methods, .members');
                        thirdLevel.forEach(function (menu) {
                            menu.style.setProperty('display', 'none', 'important');
                            menu.style.visibility = 'hidden';
                        });
                    });

                    secondLevelLink.classList.add('current');

                    // 添加专业的页面过渡效果
                    document.body.style.transition = 'opacity 0.2s ease';
                    document.body.style.opacity = '0.95';

                    // 页面加载后调用专业滚动定位
                    setTimeout(function () {
                        scrollToCurrentMenuItem();
                    }, 100);
                }
                // 类型3: 页面内锚点链接
                else if (href && href.startsWith('#')) {
                    e.preventDefault();

                    document.querySelectorAll('.sidebar-section-children a.current').forEach(function (link) {
                        link.classList.remove('current');
                    });

                    secondLevelLink.classList.add('current');
                    handleAnchorScroll(href);
                }
            }, 50);
        });
    });

    // 三级菜单点击处理
    document.querySelectorAll('.sidebar-section-children .methods a, .sidebar-section-children .members a').forEach(function (thirdLevelLink) {
        thirdLevelLink.addEventListener('click', function (e) {
            const href = this.getAttribute('href');

            if (href && href.startsWith('#')) {
                e.preventDefault();

                document.querySelectorAll('.sidebar-section-children .methods a.current, .sidebar-section-children .members a.current').forEach(function (link) {
                    link.classList.remove('current');
                });

                this.classList.add('current');

                const parentLi = this.closest('.sidebar-section-children > li');
                if (parentLi) {
                    parentLi.classList.add('expanded');

                    const methods = parentLi.querySelector('.methods');
                    const members = parentLi.querySelector('.members');
                    if (methods) {
                        methods.style.display = 'block';
                        methods.style.visibility = 'visible';
                        methods.style.setProperty('display', 'block', 'important');
                    }
                    if (members) {
                        members.style.display = 'block';
                        members.style.visibility = 'visible';
                        members.style.setProperty('display', 'block', 'important');
                    }

                    const parentLink = parentLi.querySelector('> a');
                    if (parentLink) {
                        document.querySelectorAll('.sidebar-section-children > li > a.current').forEach(function (link) {
                            link.classList.remove('current');
                        });
                        parentLink.classList.add('current');
                    }

                    // 关键修复：更新容器高度
                    const container = parentLi.closest('.sidebar-section-children-container');
                    updateContainerHeight(container, 10);
                }

                handleAnchorScroll(href);
            }
        });
    });

    function handleAnchorScroll(href) {
        const targetId = href.substring(1);
        const targetElement = document.getElementById(targetId);
        if (targetElement) {
            const headerOffset = 80;
            const elementPosition = targetElement.getBoundingClientRect().top;
            const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

            window.scrollTo({
                top: offsetPosition,
                behavior: 'smooth'
            });

            targetElement.style.transition = 'background-color 0.3s ease, border 0.3s ease';
            targetElement.style.backgroundColor = '#fff3cd';
            targetElement.style.border = '2px solid #ffeaa7';
            targetElement.style.borderRadius = '4px';

            setTimeout(function () {
                targetElement.style.backgroundColor = '';
                targetElement.style.border = '';
                targetElement.style.borderRadius = '';
                setTimeout(function () {
                    targetElement.style.transition = '';
                }, 300);
            }, 2000);
        }
    }

    function expandCurrentPageMenu() {
        const currentPath = window.location.pathname;
        const currentHash = window.location.hash;
        const currentFile = currentPath.split('/').pop();

        if (currentHash) {
            const hashLink = document.querySelector('.sidebar-section-children a[href="' + currentHash + '"]');
            if (hashLink) {
                if (hashLink.closest('.methods, .members')) {
                    hashLink.classList.add('current');
                    const parentLi = hashLink.closest('.sidebar-section-children > li');
                    if (parentLi) {
                        parentLi.classList.add('expanded');
                        const methods = parentLi.querySelector('.methods');
                        const members = parentLi.querySelector('.members');

                        if (methods) {
                            methods.style.display = 'block';
                            methods.style.visibility = 'visible';
                            methods.style.setProperty('display', 'block', 'important');
                        }
                        if (members) {
                            members.style.display = 'block';
                            members.style.visibility = 'visible';
                            members.style.setProperty('display', 'block', 'important');
                        }

                        const parentLink = parentLi.querySelector('> a');
                        if (parentLink) {
                            parentLink.classList.add('current');
                        }

                        // 关键修复：页面加载时也要更新容器高度
                        const container = parentLi.closest('.sidebar-section-children-container');
                        updateContainerHeight(container, 50);
                    }
                } else {
                    hashLink.classList.add('current');
                }
                return;
            }
        }

        document.querySelectorAll('.sidebar-section-children a').forEach(function (link) {
            const href = link.getAttribute('href');
            if (href && !href.startsWith('#')) {
                const linkFile = href.split('/').pop();
                if (currentFile === linkFile || href === currentPath) {
                    if (link.closest('.methods, .members')) {
                        link.classList.add('current');
                        const parentLi = link.closest('.sidebar-section-children > li');
                        if (parentLi) {
                            parentLi.classList.add('expanded');
                            const methods = parentLi.querySelector('.methods');
                            const members = parentLi.querySelector('.members');

                            if (methods) {
                                methods.style.display = 'block';
                                methods.style.visibility = 'visible';
                                methods.style.setProperty('display', 'block', 'important');
                            }
                            if (members) {
                                members.style.display = 'block';
                                members.style.visibility = 'visible';
                                members.style.setProperty('display', 'block', 'important');
                            }

                            const parentLink = parentLi.querySelector('> a');
                            if (parentLink) {
                                parentLink.classList.add('current');
                            }

                            // 关键修复：页面加载时更新容器高度
                            const container = parentLi.closest('.sidebar-section-children-container');
                            updateContainerHeight(container, 50);
                        }
                    } else if (link.closest('.sidebar-section-children > li')) {
                        link.classList.add('current');
                        const parentLi = link.closest('.sidebar-section-children > li');
                        const hasThirdLevel = parentLi.querySelector('.methods, .members');
                        if (hasThirdLevel) {
                            parentLi.classList.add('expanded');
                            const methods = parentLi.querySelector('.methods');
                            const members = parentLi.querySelector('.members');

                            if (methods) {
                                methods.style.display = 'block';
                                methods.style.visibility = 'visible';
                                methods.style.setProperty('display', 'block', 'important');
                            }
                            if (members) {
                                members.style.display = 'block';
                                members.style.visibility = 'visible';
                                members.style.setProperty('display', 'block', 'important');
                            }

                            // 关键修复：页面加载时更新容器高度
                            const container = parentLi.closest('.sidebar-section-children-container');
                            updateContainerHeight(container, 50);
                        }
                    }
                }
            }
        });
    }

    setTimeout(function () {
        expandCurrentPageMenu();
        scrollToCurrentMenuItem();
        // 关键修复：页面加载完成后统一更新所有容器高度
        updateAllContainerHeights(100);
    }, 150);
}

// 参考minemap-docdash的hideAllButCurrent，但适配增强版结构
function hideAllButCurrent() {
    // 默认隐藏所有三级菜单
    document.querySelectorAll('nav .methods, nav .members').forEach(function (elem) {
        elem.style.setProperty('display', 'none', 'important');
        elem.style.visibility = 'hidden';
        // 清除li上可能存在的单独样式设置，让li跟随ul状态
        elem.querySelectorAll('li').forEach(function (li) {
            li.style.removeProperty('display');
            li.style.removeProperty('visibility');
        });
    });

    // 移除所有expanded类
    document.querySelectorAll('nav .sidebar-section-children li.expanded').forEach(function (elem) {
        elem.classList.remove('expanded');
    });

    // 获取当前页面文件名
    var currentFile = window.location.pathname.split('/').pop().replace(/\.html$/, '');

    // 查找匹配的二级菜单项并展开对应的三级菜单
    document.querySelectorAll('nav .sidebar-section-children > li > a').forEach(function (link) {
        var href = link.getAttribute('href');
        if (href) {
            var linkFile = href.replace(/\.html$/, '').split('/').pop();
            if (currentFile === linkFile) {
                // 高亮当前二级菜单
                link.classList.add('current');

                // 展开对应的三级菜单
                var li = link.closest('li');
                var methodsList = li.querySelector('.methods');
                var membersList = li.querySelector('.members');

                if (methodsList || membersList) {
                    li.classList.add('expanded');
                    if (methodsList) {
                        methodsList.style.setProperty('display', 'block', 'important');
                        methodsList.style.visibility = 'visible';
                        // 关键修复：清除li的单独样式，让它们跟随ul显示
                        methodsList.querySelectorAll('li').forEach(function (childLi) {
                            childLi.style.removeProperty('display');
                            childLi.style.removeProperty('visibility');
                        });
                    }
                    if (membersList) {
                        membersList.style.setProperty('display', 'block', 'important');
                        membersList.style.visibility = 'visible';
                        // 关键修复：清除li的单独样式，让它们跟随ul显示
                        membersList.querySelectorAll('li').forEach(function (childLi) {
                            childLi.style.removeProperty('display');
                            childLi.style.removeProperty('visibility');
                        });
                    }
                }

                // 确保父级section是展开的
                var parentSection = li.closest('.sidebar-section');
                var titleElement = parentSection.querySelector('.sidebar-section-title');
                if (titleElement && titleElement.classList.contains('with-arrow')) {
                    titleElement.setAttribute('data-isopen', 'true');
                    var container = parentSection.querySelector('.sidebar-section-children-container');
                    if (container) {
                        container.style.maxHeight = 'none';
                        var actualHeight = container.scrollHeight;
                        container.style.maxHeight = actualHeight + 'px';
                        container.style.overflow = 'visible';
                    }
                }
            }
        }
    });

    // 检查三级菜单项是否匹配当前页面的锚点
    var currentHash = window.location.hash.substring(1);
    if (currentHash) {
        document.querySelectorAll('nav .methods a, nav .members a').forEach(function (link) {
            var href = link.getAttribute('href');
            if (href && href.includes('#' + currentHash)) {
                link.classList.add('current');

                // 确保父级菜单展开
                var parentLi = link.closest('.methods, .members').closest('li');
                if (parentLi) {
                    parentLi.classList.add('expanded');
                    var methodsList = parentLi.querySelector('.methods');
                    var membersList = parentLi.querySelector('.members');
                    if (methodsList) {
                        methodsList.style.setProperty('display', 'block', 'important');
                        methodsList.style.visibility = 'visible';
                        // 清除li的单独样式，让它们跟随ul
                        methodsList.querySelectorAll('li').forEach(function (childLi) {
                            childLi.style.removeProperty('display');
                            childLi.style.removeProperty('visibility');
                        });
                    }
                    if (membersList) {
                        membersList.style.setProperty('display', 'block', 'important');
                        membersList.style.visibility = 'visible';
                        // 清除li的单独样式，让它们跟随ul
                        membersList.querySelectorAll('li').forEach(function (childLi) {
                            childLi.style.removeProperty('display');
                            childLi.style.removeProperty('visibility');
                        });
                    }

                    var parentLink = parentLi.querySelector('> a');
                    if (parentLink) {
                        parentLink.classList.add('current');
                    }
                }
            }
        });
    }
}

// 改进的搜索功能 - 参考minemap-docdash思路
function performNavSearch(search) {
    var searchAttr = 'data-search-mode';

    // 清除之前的高亮
    document.querySelectorAll('.search-highlight').forEach(function (elem) {
        var parent = elem.parentNode;
        parent.replaceChild(document.createTextNode(elem.textContent), elem);
        parent.normalize();
    });

    if (search.length === 0) {
        // 取消搜索模式
        document.documentElement.removeAttribute(searchAttr);

        // 重置所有显示状态
        document.querySelectorAll("nav .sidebar-section").forEach(function (parent) {
            parent.style.display = "block";
        });
        document.querySelectorAll("nav .sidebar-section-children li").forEach(function (child) {
            child.style.display = "block";
        });
        document.querySelectorAll("nav .sidebar-section-children a").forEach(function (elem) {
            elem.innerHTML = elem.textContent; // 移除高亮
            elem.classList.remove('search-current'); // 移除搜索时添加的样式
        });

        // 重要：恢复原有的菜单状态
        // 先隐藏所有三级菜单
        document.querySelectorAll('.methods, .members').forEach(function (elem) {
            elem.style.display = 'none';
            elem.style.visibility = 'hidden';
        });

        // 移除所有expanded类
        document.querySelectorAll('.sidebar-section-children li').forEach(function (li) {
            li.classList.remove('expanded');
        });

        // 重置容器高度
        document.querySelectorAll('.sidebar-section-children-container').forEach(function (container) {
            container.style.maxHeight = '';
            container.style.overflow = '';
        });

        // 恢复当前页面的菜单状态
        setTimeout(function () {
            expandCurrentPageMenu();
            updateAllContainerHeights();
        }, 50);

    } else {
        // 进入搜索模式
        document.documentElement.setAttribute(searchAttr, '');

        // 显示所有一级菜单
        document.querySelectorAll("nav .sidebar-section").forEach(function (parent) {
            parent.style.display = "block";
        });

        // 隐藏所有二级菜单项
        document.querySelectorAll("nav .sidebar-section-children li").forEach(function (child) {
            child.style.display = "none";
        });

        // 显示匹配的结果并高亮
        document.querySelectorAll("nav .sidebar-section-children a").forEach(function (elem) {
            if (contains(elem, search)) {
                // 高亮匹配的文本
                var originalText = elem.textContent;
                elem.innerHTML = highlightSearchTerm(originalText, search);

                var li = elem.closest('li');
                if (li) {
                    li.style.display = "block";

                    // 确保父级容器也显示并展开
                    var parentSection = li.closest('.sidebar-section');
                    if (parentSection) {
                        parentSection.style.display = "block";

                        // 展开父级容器
                        var container = parentSection.querySelector('.sidebar-section-children-container');
                        if (container) {
                            container.style.maxHeight = 'none';
                            container.style.overflow = 'visible';
                        }
                    }

                    // 如果是三级菜单项，确保其显示
                    if (li.querySelector('.methods, .members')) {
                        var thirdLevel = li.querySelector('.methods, .members');
                        if (thirdLevel) {
                            thirdLevel.style.display = 'block';
                            thirdLevel.style.visibility = 'visible';
                        }
                    }
                }
            }
        });

        // 同时搜索三级菜单项
        document.querySelectorAll('.methods a, .members a').forEach(function (elem) {
            if (contains(elem, search)) {
                // 高亮匹配的文本
                var originalText = elem.textContent;
                elem.innerHTML = highlightSearchTerm(originalText, search);

                var li = elem.closest('li');
                var parentLi = elem.closest('.sidebar-section-children > li');

                if (li && parentLi) {
                    // 显示三级菜单项
                    li.style.display = 'block';

                    // 显示父级二级菜单项
                    parentLi.style.display = 'block';

                    // 显示三级菜单容器
                    var thirdLevelContainer = li.closest('.methods, .members');
                    if (thirdLevelContainer) {
                        thirdLevelContainer.style.display = 'block';
                        thirdLevelContainer.style.visibility = 'visible';
                    }

                    // 确保父级section显示
                    var parentSection = parentLi.closest('.sidebar-section');
                    if (parentSection) {
                        parentSection.style.display = 'block';

                        var container = parentSection.querySelector('.sidebar-section-children-container');
                        if (container) {
                            container.style.maxHeight = 'none';
                            container.style.overflow = 'visible';
                        }
                    }
                }
            }
        });

        // 隐藏没有匹配结果的section
        document.querySelectorAll("nav .sidebar-section").forEach(function (parent) {
            var hasVisibleChildren = false;

            // 检查二级菜单
            parent.querySelectorAll(".sidebar-section-children > li").forEach(function (child) {
                if (child.style.display !== "none") {
                    hasVisibleChildren = true;
                }
            });

            // 检查三级菜单
            parent.querySelectorAll(".methods li, .members li").forEach(function (child) {
                if (child.style.display !== "none") {
                    hasVisibleChildren = true;
                }
            });

            if (!hasVisibleChildren) {
                parent.style.display = "none";
            }
        });
    }
}

// 防止横向滚动的处理
function preventHorizontalScroll() {
    // 监听窗口大小变化
    window.addEventListener('resize', function () {
        var main = document.getElementById('main');
        var nav = document.querySelector('nav');
        if (main && nav) {
            var isCollapsed = nav.classList.contains('sidebar-collapsed');

            if (isCollapsed) {
                main.style.marginLeft = 'var(--sidebar-collapsed-width)';
                main.style.maxWidth = 'calc(100vw - var(--sidebar-collapsed-width))';
            } else {
                main.style.marginLeft = 'var(--sidebar-width)';
                main.style.maxWidth = 'calc(100vw - var(--sidebar-width))';
            }
        }
    });

    // 处理内容溢出
    document.querySelectorAll('#main pre, #main code').forEach(function (elem) {
        elem.style.overflowX = 'auto';
        elem.style.wordWrap = 'break-word';
    });
}

// 移动端处理
function initMobileHandling() {
    if (window.innerWidth <= 768) {
        var nav = document.querySelector('nav');
        var navTrigger = document.getElementById('nav-trigger');

        if (nav && navTrigger) {
            navTrigger.addEventListener('change', function () {
                if (this.checked) {
                    nav.classList.add('sidebar-show');
                } else {
                    nav.classList.remove('sidebar-show');
                }
            });
        }
    }
}

// 新增：滚动到当前菜单项的函数 - 专业版本
function scrollToCurrentMenuItem() {
    const currentMenuItem = document.querySelector('nav .sidebar-section-children a.current');
    if (currentMenuItem) {
        const nav = document.querySelector('nav');
        const navHeader = document.querySelector('.nav-header');
        const sidebarContent = document.querySelector('.sidebar-content');

        if (!nav || !navHeader || !sidebarContent) return;

        // 计算nav-header的高度（包括padding和border）
        const navHeaderHeight = navHeader.offsetHeight;

        // 获取当前菜单项相对于侧边栏内容的位置
        const menuItemRect = currentMenuItem.getBoundingClientRect();
        const sidebarContentRect = sidebarContent.getBoundingClientRect();
        const navRect = nav.getBoundingClientRect();

        // 计算目标滚动位置：菜单项应该出现在nav-header下方
        const targetOffset = navHeaderHeight + 20; // 20px的专业间距
        const currentOffset = menuItemRect.top - navRect.top;

        // 如果菜单项不在理想位置，进行滚动调整
        if (currentOffset < targetOffset || currentOffset > targetOffset + 100) {
            // 计算需要滚动的距离
            const scrollDistance = currentOffset - targetOffset;
            const currentScrollTop = sidebarContent.scrollTop;

            // 平滑滚动到目标位置
            sidebarContent.scrollTo({
                top: currentScrollTop + scrollDistance,
                behavior: 'smooth'
            });
        }

        // 添加专业的视觉反馈效果
        currentMenuItem.style.transition = 'all 0.3s ease';
        const originalStyles = {
            backgroundColor: currentMenuItem.style.backgroundColor,
            transform: currentMenuItem.style.transform,
            boxShadow: currentMenuItem.style.boxShadow
        };

        // 应用高亮效果
        currentMenuItem.style.backgroundColor = 'var(--primary-color)';
        currentMenuItem.style.color = '#ffffff';
        currentMenuItem.style.transform = 'translateX(3px)';
        currentMenuItem.style.boxShadow = '0 2px 8px rgba(34, 80, 180, 0.3)';

        // 1.5秒后恢复原始样式
        setTimeout(function () {
            currentMenuItem.style.backgroundColor = originalStyles.backgroundColor;
            currentMenuItem.style.color = '';
            currentMenuItem.style.transform = originalStyles.transform;
            currentMenuItem.style.boxShadow = originalStyles.boxShadow;

            setTimeout(function () {
                currentMenuItem.style.transition = '';
            }, 300);
        }, 1500);
    }
}

// 修改initEnhancedFeatures函数，优化初始化顺序
function initEnhancedFeatures() {
    // 初始化主题（最先执行，避免闪烁）
    initTheme();

    // 初始化字体调整
    initFontSize();

    // 初始化折叠功能
    initAccordion();

    // 延迟执行菜单相关初始化，减少抖动
    requestAnimationFrame(function () {
        // 初始化菜单高亮
        initMenuHighlight();

        // 初始化菜单项处理
        initMenuItemHandlers();
    });

    // 其他初始化
    initSidebarToggle();
    preventHorizontalScroll();
    initMobileHandling();
    bindEventListeners();
}

// 绑定事件监听器
function bindEventListeners() {
    // 主题切换按钮
    var themeToggle = document.querySelector('.theme-toggle');
    if (themeToggle) {
        themeToggle.addEventListener('click', toggleTheme);
    }

    // 全局搜索按钮
    var globalSearchBtn = document.querySelector('.global-search-button');
    if (globalSearchBtn) {
        globalSearchBtn.addEventListener('click', showGlobalSearch);
    }

    // 字体调整按钮
    var fontSizeBtn = document.querySelector('.font-size-button');
    if (fontSizeBtn) {
        fontSizeBtn.addEventListener('click', function () {
            showFontSizeTooltip(fontSizeBtn);
        });
    }

    // 左侧菜单搜索框 - 使用防抖优化性能
    var navSearch = document.getElementById('nav-search');
    if (navSearch) {
        var searchTimeout;

        // 输入事件
        navSearch.addEventListener('input', function (e) {
            clearTimeout(searchTimeout);
            var search = this.value.toUpperCase();
            searchTimeout = setTimeout(function () {
                performNavSearch(search);
            }, 200); // 200ms防抖
        });

        // 支持ESC键清空搜索
        navSearch.addEventListener('keydown', function (e) {
            if (e.key === 'Escape') {
                this.value = '';
                performNavSearch('');
                this.blur();
            }
        });

        // 失去焦点时如果搜索框为空，确保重置状态
        navSearch.addEventListener('blur', function (e) {
            if (!this.value.trim()) {
                performNavSearch('');
            }
        });
    }


    // 全局搜索关闭按钮
    var searchCloseBtn = document.getElementById('search-close-button');
    if (searchCloseBtn) {
        searchCloseBtn.addEventListener('click', hideGlobalSearch);
    }

    // ESC键关闭全局搜索
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') {
            hideGlobalSearch();
        }
    });

    // 点击搜索容器外部关闭搜索
    var searchContainer = document.getElementById('global-search-container');
    if (searchContainer) {
        searchContainer.addEventListener('click', function (e) {
            if (e.target === searchContainer) {
                hideGlobalSearch();
            }
        });
    }
}

// 字体调整弹窗
function showFontSizeTooltip(button) {
    var existingTooltip = document.querySelector('.font-size-tooltip');
    if (existingTooltip) {
        existingTooltip.remove();
        return;
    }

    var tooltip = document.createElement('div');
    tooltip.className = 'font-size-tooltip';
    tooltip.innerHTML = createFontSizeTooltip();

    var rect = button.getBoundingClientRect();
    tooltip.style.position = 'fixed';
    tooltip.style.top = (rect.bottom + 10) + 'px';
    tooltip.style.right = '10px';
    tooltip.style.zIndex = '1000';

    document.body.appendChild(tooltip);

    setTimeout(function () {
        document.addEventListener('click', function closeTooltip(e) {
            if (!tooltip.contains(e.target) && e.target !== button) {
                tooltip.remove();
                document.removeEventListener('click', closeTooltip);
            }
        });
    }, 100);
}



// 确保在DOM加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initEnhancedFeatures);
} else {
    initEnhancedFeatures();
}

// 全局搜索相关函数
function showGlobalSearch() {
    var searchContainer = document.getElementById('global-search-container');
    var searchInput = document.getElementById('global-search-input');

    if (searchContainer) {
        searchContainer.style.display = 'flex';
        if (searchInput) {
            searchInput.focus();
        }
    }
}

function hideGlobalSearch() {
    var searchContainer = document.getElementById('global-search-container');
    if (searchContainer) {
        searchContainer.style.display = 'none';
    }
}


// 侧边栏折叠功能
function initSidebarToggle() {
    var sidebarToggleBtn = document.getElementById('sidebar-toggle');
    var nav = document.querySelector('nav');
    var main = document.getElementById('main');

    if (sidebarToggleBtn && nav) {
        sidebarToggleBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();

            // 切换折叠状态
            nav.classList.toggle('sidebar-collapsed');

            // 调整主内容区域的边距
            if (main) {
                if (nav.classList.contains('sidebar-collapsed')) {
                    main.style.marginLeft = 'var(--sidebar-collapsed-width)';
                    main.style.maxWidth = 'calc(100vw - var(--sidebar-collapsed-width))';
                } else {
                    main.style.marginLeft = 'var(--sidebar-width)';
                    main.style.maxWidth = 'calc(100vw - var(--sidebar-width))';
                }
            }

            // 保存折叠状态到localStorage
            var isCollapsed = nav.classList.contains('sidebar-collapsed');
            localStorage.setItem('sidebar-collapsed', isCollapsed.toString());
        });

        // 恢复保存的折叠状态
        var savedState = localStorage.getItem('sidebar-collapsed');
        if (savedState === 'true') {
            nav.classList.add('sidebar-collapsed');
            if (main) {
                main.style.marginLeft = 'var(--sidebar-collapsed-width)';
                main.style.maxWidth = 'calc(100vw - var(--sidebar-collapsed-width))';
            }
        }
    }
}

(function () {
    var fontSize = getFontSize();
    var fontSizeInLocalStorage = localStorage.getItem(fontSizeLocalStorageKey);

    if (fontSizeInLocalStorage) {
        var n = Number.parseInt(fontSizeInLocalStorage, 10);
        if (n !== fontSize) {
            updateFontSize(n);
        }
    } else {
        updateFontSize(fontSize);
    }
})();